package com.sms.starter.config;

import com.sms.starter.SmsService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * 短信自动配置类
 *
 * @Author Sans
 * @CreateTime 2019/4/20
 * @attention
 */
@Configuration  //注释使类成为bean的工厂
@ConditionalOnClass(SmsService.class)   //有当SmsService类存在于classpath中时才会进行相应的实例化
// 负责导入这个已经绑定了属性的bean到spring容器中，使@ConfigurationProperties注解生效
@EnableConfigurationProperties(SmsProperties.class) 
public class SmsAutoConfiguration {

    /**
     * 注入属性配置类
     */
    @Resource
    private SmsProperties smsProperties;

    @Bean
    //当容器中不存在SmsService的对象时再进行实例化
    @ConditionalOnMissingBean(SmsService.class)
    // @ConditionalOnProperty指定了配置文件中sms.enabled=true时才进行相应的实例化。
    @ConditionalOnProperty(prefix = "sms", value = "enabled", havingValue = "true")
    public SmsService getBean(){
        SmsService smsService = new SmsService(smsProperties);
        return smsService;
    }
}
